package com.imy.touch.root.client;

import android.net.LocalSocket;
import android.net.LocalSocketAddress;

import com.imy.common.util.ALog;

import java.net.InetAddress;
import java.net.Socket;

public abstract class  SocketClient implements Runnable {
    private boolean connect = false;
    private LocalSocketClientTransceiver transceiver;

    /**
     * 建立连接
     * <p>
     * 连接的建立将在新线程中进行
     * <p>
     * 连接建立成功，回调{@code onConnect()}
     * <p>
     * 连接建立失败，回调{@code onConnectFailed()}
     */
    public void connect() {
        new Thread(this).start();
    }
    @Override
    public void run() {
        try {
            //获取自身IP
            LocalSocket localSocket = new LocalSocket();
            transceiver = new LocalSocketClientTransceiver(localSocket) {
                @Override
                public void onReceive( String s) {
                    SocketClient.this.onReceive(this, s);
                }
                @Override
                public void onDisconnect() {
                    connect = false;
                    SocketClient.this.onDisconnect(this);
                }
            };
            LocalSocketAddress address= new LocalSocketAddress("rootouch");
            localSocket.connect(address);
            transceiver.start();
            connect = true;
            this.onConnect(transceiver);
        } catch (Exception e) {
            ALog.te("clientSocket error:"+e.getMessage());
            e.printStackTrace();
            this.onConnectFailed();
        }
    }


    /**
     * 断开连接
     * <p>
     * 连接断开，回调{@code onDisconnect()}
     */
    public void disconnect() {
        if (transceiver != null) {
            transceiver.stop();
            transceiver = null;
        }
    }

    /**
     * 判断是否连接
     *
     * @return 当前处于连接状态，则返回true
     */
    public boolean isConnected() {
        return connect;
    }


    /**
     * 获取Socket收发器
     *
     * @return 未连接则返回null
     */
    public LocalSocketClientTransceiver getTransceiver() {
        return isConnected() ? transceiver : null;
    }

    /**
     * 连接建立
     *
     * @param transceiver SocketTransceiver对象
     */
    public abstract void onConnect(LocalSocketClientTransceiver transceiver);

    /**
     * 连接建立失败
     */
    public abstract void onConnectFailed();

    /**
     * 接收到数据
     * <p>
     * 注意：此回调是在新线程中执行的
     *
     * @param transceiver SocketTransceiver对象
     * @param s           字符串
     */
    public abstract void onReceive(LocalSocketClientTransceiver transceiver, String s);

    /**
     * 连接断开
     * <p>
     * 注意：此回调是在新线程中执行的
     *
     * @param transceiver SocketTransceiver对象
     */
    public abstract void onDisconnect(LocalSocketClientTransceiver transceiver);
}
